/**
 * @author : 乔磊磊
 * @ide    : WebStorm
 * @date   : 2025/2/18 星期二 21:25
 * @desc   :
 */
import {_decorator, Component} from 'cc';
import {eventMgr} from "../event"
import {logger} from "../log";
import {IEventMapping} from "./IEventMapping";
const {ccclass} = _decorator;

@ccclass('EventComponent')
export class EventComponent extends Component {
    private registeredEvents: IEventMapping<(...args: any[]) => void>[] = [];

    protected on<TFunction extends (...any: any[]) => void>(eventName: string, callback: TFunction, target?: any): typeof callback {
        this.registeredEvents.push({
            type: eventName,
            callback: callback,
            target: target,
        })
        this.registerEvent(eventName, callback, target);
        return eventMgr.on(eventName, callback, target)
    }

    protected once<TFunction extends (...any: any[]) => void>(eventName: string, callback: TFunction, target?: any): typeof callback {
        this.registerEvent(eventName, callback, target);
        return eventMgr.once(eventName, callback, target)
    }

    protected targetOff(target: any) {
        this.registeredEvents = this.registeredEvents.filter(event => event.target !== target);
        eventMgr.targetOff(target)
    }

    protected emit(eventName: string, ...args:unknown[]) {
        if (args.length > 5) {
            logger.warn(`emit args length > 5, Invalid parameters will not take effect`)
        }
        eventMgr.emit(eventName, args[0], args[1], args[2], args[3], args[4])
    }

    protected onDestroy() {
        this.registeredEvents.forEach(event => {
            eventMgr.off(event.type, event.callback, event.target);
        });
        this.registeredEvents = [];
    }

    private registerEvent<TFunction extends (...args: any[]) => void>(eventName: string,callback: TFunction,target?: any): void {
        this.registeredEvents.push({
            type: eventName,
            callback: callback,
            target: target,
        });
    }
}
